package cloud.demarcia.crawler3;

import cloud.demarcia.crawler3.entities.InitInfo;
import cloud.demarcia.crawler3.entities.Page;
import cloud.demarcia.crawler3.utils.Browser;
import cloud.demarcia.crawler3.utils.PageGetter;
import cloud.demarcia.crawler3.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.net.MalformedURLException;
import java.net.URL;

@Component
public class Starter implements CommandLineRunner {

    private final InitInfo info;
    private final PageGetter pageGetter;

    @Autowired
    public Starter(InitInfo info, PageGetter pageGetter) {
        this.info = info;
        this.pageGetter = pageGetter;
    }

    @Override
    public void run(String... args) throws MalformedURLException {
        StringUtils stringUtils=new StringUtils();
        URL url=new URL(stringUtils.urlLegalize(info.getUrl()));
        Page firstPage=new Page(url, info.getProcessor());
        pageGetter.addPage(firstPage);
        try {
            pageGetter.runQueue();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Browser.shutdown();
        System.out.println("[CRAWLER] Task finished, this application will soon" +
                " terminated." );
        System.out.println("[CRAWLER] Bye!");
    }
}
